package com.ssy.lingxi.purchase.serviceimpl.tender;

import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.purchase.api.dto.request.tender.StatusRequest;
import com.ssy.lingxi.purchase.entity.tender.Template;
import com.ssy.lingxi.purchase.entity.tender.TemplateContent;
import com.ssy.lingxi.purchase.repository.tender.InviteTenderRepository;
import com.ssy.lingxi.purchase.repository.tender.TemplateContentRepository;
import com.ssy.lingxi.purchase.repository.tender.TemplateRepository;
import com.ssy.lingxi.purchase.service.tender.ITemplateService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评标模板实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class TemplateServiceImpl implements ITemplateService {

    @Resource
    private TemplateRepository templateRepository;

    @Resource
    private InviteTenderRepository inviteTenderRepository;

    @Resource
    private TemplateContentRepository templateContentRepository;

    /**
     * 查询评标模板列表
     * @param pageVO 分页实体
     * @param name 评标模板名称
     * @return
     */
    @Override
    public Page<Template> getTemplateList(UserLoginCacheDTO sysUser, PageVO pageVO, String name, Boolean status){
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return templateRepository.findAll(getSpecification(sysUser, name, status), page);
    }

    /**
     * 查询评标模板
     * @return id
     */
    @Override
    public Template getTemplate(Long id){
        return templateRepository.findById(id).orElse(null);
    }

    /**
     * 添加/修改评标模板
     * @param template
     * @return
     */
    @Override
    public String saveOrUpdateTemplate(UserLoginCacheDTO sysUser, Template template){
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Long userId = sysUser.getUserId();
        //判断名称是否重复
        Long id = template.getId();
        String name = template.getName();
        List<Template> old_template;
        List<Long> templateContentIdList = new ArrayList<>();
        if(id != null && id > 0){
            Template currentTemplate = templateRepository.findById(id).orElse(null);
            if(currentTemplate != null){
                templateContentIdList = currentTemplate.getTemplateContentList().stream().map(TemplateContent::getId).collect(Collectors.toList());
                old_template = templateRepository.findByMemberIdAndMemberRoleIdAndNameAndIdNot(memberId, memberRoleId, name, id);
            }else{
                throw new BusinessException(ResponseCode.PURCHASE_TENDER_TEMPLATE_NOT_EXIST);
            }
        }else{
            old_template = templateRepository.findByMemberIdAndMemberRoleIdAndName(memberId, memberRoleId, name);

        }
        if(!old_template.isEmpty()){
            throw new BusinessException(ResponseCode.PURCHASE_TENDER_TEMPLATE_NAME_EXIST);
        }

        template.setMemberId(memberId);
        template.setMemberName(sysUser.getCompany());
        template.setMemberRoleId(memberRoleId);
        template.setMemberRoleName(sysUser.getMemberRoleName());
        template.setUserId(userId);
        template.setUserName(sysUser.getUserName());
        template.setCreateTime(System.currentTimeMillis());
        //评标模板内容
        List<TemplateContent> templateContentList = template.getTemplateContentList();
        List<Long> finalTemplateContentIdList = templateContentIdList;
        templateContentList.forEach(templateContent -> {
            Long templateContentId = templateContent.getId();
            if(finalTemplateContentIdList.size() > 0){
                finalTemplateContentIdList.remove(templateContentId);
            }
            templateContent.setTemplate(template);
        });
        //数据库持久化对象
        templateRepository.saveAndFlush(template);

        if(finalTemplateContentIdList.size() > 0){
            templateContentRepository.deleteByIdIn(finalTemplateContentIdList);
        }
        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 修改评标模板状态
     * @param sysUser
     * @param statusRequest
     * @return
     */
    @Override
    public Boolean updateTemplateStatus(UserLoginCacheDTO sysUser, StatusRequest statusRequest) {
        Long id = statusRequest.getId();
        Boolean status = statusRequest.getStatus();
        if(id != null){
            Template template = templateRepository.findById(id).orElse(null);
            if(template != null){
                template.setStatus(status);
                templateRepository.saveAndFlush(template);
                return true;
            }
        }
        throw new BusinessException(ResponseCode.PURCHASE_TENDER_TEMPLATE_NOT_EXIST);
    }

    /**
     * 批量删除评标模板
     * @param idList
     * @return
     */
    @Override
    public String deleteBatchTemplate(UserLoginCacheDTO sysUser, List<Long> idList) {
        //判断评标模板是否存在
        List<Template> templateList = templateRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), idList);
        if(templateList.isEmpty() || templateList.size() != idList.size()){
            throw new BusinessException(ResponseCode.PURCHASE_TENDER_TEMPLATE_NOT_EXIST);
        }

        //判断招标是否引用过该模板
        Boolean flag = inviteTenderRepository.existsByTemplateIdIn(idList);
        if(flag){
            throw new BusinessException(ResponseCode.PURCHASE_TENDER_TEMPLATE_IS_USE);
        }

        templateRepository.deleteAll(templateList);
        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 查询该评标模板是否被使用
     * @param id 评标模板id
     * @return
     */
    @Override
    public Boolean getTemplateIsUse(Long id) {
        //判断招标是否引用过该模板
        return inviteTenderRepository.existsByTemplateId(id);
    }

    /**
     * 构建查询条件
     * @param sysUser
     * @return
     */
    private Specification<Template> getSpecification(UserLoginCacheDTO sysUser, String name, Boolean status){
        return new Specification<Template>() {
            @Override
            public Predicate toPredicate(Root<Template> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate finalConditions = criteriaBuilder.conjunction();
                if(!StringUtils.isEmpty(name)){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%"));
                }
                if(status != null){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("status"), status));
                }
                if(sysUser.getMemberId() != null && sysUser.getMemberId() > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId").as(Long.class), sysUser.getMemberId()));
                }
                if(sysUser.getMemberRoleId() != null && sysUser.getMemberRoleId() > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId").as(Long.class), sysUser.getMemberRoleId()));
                }
                query.orderBy(criteriaBuilder.desc(root.get("id")));
                return finalConditions;
            }
        };
    }
}

